package cn.vc.shop.service;

import cn.vc.shop.entity.dto.OrderForGoodsDto;
import cn.vc.shop.entity.po.OrderForGoods;
import cn.vc.shop.mapper.OrderForGoodsMapper;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;

@Service
public class OrderForGoodsService {
    private final OrderForGoodsMapper orderForGoodsMapper;

    @Autowired
    public OrderForGoodsService(OrderForGoodsMapper orderForGoodsMapper) {
        this.orderForGoodsMapper = orderForGoodsMapper;
    }


    /**
     * 添加订单
     * @param userId
     * @param commodityId
     * @param num
     * @return
     */
    public boolean insert(Long userId, Long commodityId, Integer num) {
        OrderForGoods ofg = new OrderForGoods();
        ofg.setUserId(userId);
        ofg.setCommodityId(commodityId);
        ofg.setNum(num);
        return orderForGoodsMapper.insert(ofg)==1;
    }
    /**
     * 添加订单
     * @param orderForGoods 需要添加的订单
     * @return
     */
    public boolean insert(OrderForGoods orderForGoods) {
        return orderForGoodsMapper.insert(orderForGoods)==1;
    }



    public boolean delete(Long id) {
        return orderForGoodsMapper.deleteById(id)==1;
    }


    /**
     * 查询指定用户的订单
     * @param userId 用户ID
     * @return
     */
    public List<OrderForGoodsDto> selectGoodsByUserId(Long userId) {
        LambdaQueryWrapper<OrderForGoods> lqw = new LambdaQueryWrapper<>();
        lqw.eq(OrderForGoods::getUserId, userId);
        List<OrderForGoods> orderForGoodsList = orderForGoodsMapper.selectList(lqw);
        List<OrderForGoodsDto> orderForGoodsDtoList = orderForGoodsList.stream().map(o -> {
            OrderForGoodsDto dto = new OrderForGoodsDto();
            BeanUtils.copyProperties(o, dto);
            dto.setId(o.getId().toString());
            return dto;
        }).collect(Collectors.toList());
        return orderForGoodsDtoList;
    }
    /**
     * 查询是否限额
     * @param userId 用户ID
     * @param commodityId 商品ID
     * @param limitedNum 限量额
     * @return
     */
    public boolean selectIsLimited(Long userId, Long commodityId, Integer limitedNum) {
        LambdaQueryWrapper<OrderForGoods> lqw = new LambdaQueryWrapper<>();
        lqw.eq(OrderForGoods::getUserId, userId).eq(OrderForGoods::getCommodityId, commodityId);
        List<OrderForGoods> orderForGoodsList = orderForGoodsMapper.selectList(lqw);
        Integer num = 0;
        for (OrderForGoods o : orderForGoodsList) {
            num += o.getNum();
        }
        return num >= limitedNum;
    }
}
